package com.example.myview;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Shader;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;

import com.example.bean.CMinute;
import com.example.bean.CrossBean;
import com.example.bean.FenshiDataResponse;
import com.example.utils.ColorUtil;
import com.example.utils.ColorUtil2;
import com.example.utils.DrawUtils;
import com.example.utils.GridUtils;
import com.example.utils.LineUtil;
import com.example.utils.NumberUtil2;

import java.util.ArrayList;


/**
 * Created by Administrator on 2016/10/25.
 */
public class FenshiView extends ChartView {
    //x坐标的索引
    int[] index;
    //分时数据
    private FenshiDataResponse data ;
    //补全后的所有点
    private ArrayList<CMinute> minutes;
    //所有价格
    private float[] price;
    //所有均线数据
    private float[] average;
    //分时线昨收
    private double yd;

    //是否白盘夜盘一起显示
    private boolean hasNight;

    private double yMax;
    private double yMin;
    private float xUnit;
    protected double yUnit;
    /**
     * 价格精度 默认2
     */
    private int scale_price=2;

    public FenshiView(Context context, AttributeSet attrs) {
        super(context, attrs);
        setLayerType(View.LAYER_TYPE_SOFTWARE, null);
    }

    @Override
    protected boolean onViewScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
        return false;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if(crossView != null) {
            if (crossView.getVisibility() == View.VISIBLE) {
                 crossView.gestureDetector.onTouchEvent(event);

                return false;
            }
        }

        if (gestureDetector != null)
            gestureDetector.onTouchEvent(event);
        return true;
    }


    @Override
    protected void init() {


        if(minutes== null) return;
        yd = data.getParam().getLast();
        hasNight = LineUtil.hasNight(data.getParam().getDuration());
        xUnit = mWidth / LineUtil.getShowCount(data.getParam().getDuration());
        //计算最大最小值
        boolean first = true;
        for(CMinute c : data.getData()) {
            if(first) {
                first = false;
                yMax = c.getPrice();
                yMin = c.getPrice();
            }
            yMax = c.getPrice() > yMax ? c.getPrice() : yMax;
            //yMax = c.getAverage() > yMax ? c.getAverage() : yMax;
            if(c.getPrice() != 0)
                yMin = c.getPrice() < yMin ? c.getPrice() : yMin;
            //if(c.getAverage() != 0 && c.getAverage() != 0.01)
                //yMin = c.getAverage() < yMin ? c.getAverage() : yMin;
        }

        //得到对称的最大最小值
        double upPercent = (yMax - yd) / yd;
        double downPercent = (yMin - yd) / yd;
        double maxPercent = Math.abs(upPercent) > Math.abs(downPercent) ? upPercent : downPercent;
        double halfPercent = maxPercent / 2d;
        //计算出最大价格
        double diff = Math.abs(yMax - yd) > Math.abs(yMin - yd) ? Math.abs(yMax - yd) : Math.abs(yMin - yd);
        String p1 = NumberUtil2.getString(yd + diff+"","1",scale_price);
        String p2 = NumberUtil2.getString(yd - diff+"","1",scale_price);
        yMax=Double.valueOf(p1);
        yMin=Double.valueOf(p2);

        yUnit =  (yMax - yMin) / (mainH);
    }

    @Override
    protected void drawGrid(Canvas canvas) {

        //1,画网格
        if(data != null && data.getParam() != null && LineUtil.isIrregular(data.getParam().getDuration())&&1==2) {
            //如果是不规则网格画不规则网格
            GridUtils.drawIrregularGrid(canvas, mWidth, mainH, data.getParam().getDuration());
            GridUtils.drawIrregularIndexGrid(canvas, indexStartY, mWidth, indexH, data.getParam().getDuration());
        } else {
//            if(hasNight) {
//                GridUtils.drawNightGrid(canvas, mWidth, mainH);
//                GridUtils.drawNightIndexGrid(canvas, indexStartY, mWidth, indexH);
//            } else {
//                GridUtils.drawGrid(canvas, mWidth, mainH);
//                GridUtils.drawIndexGrid(canvas, indexStartY, mWidth, indexH);
//            }
            GridUtils.drawGrid(this,canvas, mWidth, mainH);
            GridUtils.drawIndexGrid(this,canvas,indexStartY-zhibiaoY, mWidth, indexH+zhibiaoY);
        }

    }

    @Override
    protected void drawStyle(Canvas canvas) {

    }
   public void updateDataAndInvalidate(CMinute last)
   {
       if(minutes!=null&&minutes.size()>0) {
           CMinute clast=minutes.get(minutes.size()-1);
           long ctime=clast.getTime()/60;
           long time=last.getTime()/60;
           if(time>ctime)
           {
               data.addData(last);
               minutes.add(last);

           }
          else
           {
               double d = Double.parseDouble(NumberUtil2.getAddString(clast.getCount()+ "", last.getCount() + "", scale_price));
               clast.setCount((long) d);
               clast.setPrice(last.getPrice());
               clast.setAverage(last.getAverage());
               clast.setChange(last.getChange());
               clast.setChg(last.getChg());
               clast.setTime(clast.getTime());
               clast.setRate(clast.getRate());
               clast.setMoney(clast.getMoney());
           }
           postInvalidate();
       }
   }
    /**
     * 重新画分时图
     * @param data
     */
    public void setDataAndInvalidate(FenshiDataResponse data) {
        this.data = data;

        LineUtil.initFenShiPoint(data.getParam().getDuration());

        minutes=(ArrayList<CMinute>) data.getData();

        //minutes = LineUtil.getAllFenshiData4(data);
//       ArrayList<CMinute> test=new ArrayList<>();
//       for(int a=0;a<data.getData().size();a++)
//       {
//           test.add(data.getData().get(a));
//       }
//       minutes=test;
        postInvalidate();
    }

    @Override
    protected void drawText(Canvas canvas) {
        if(minutes== null) return;
        DrawUtils.setScale(scale_price);
        //画y轴价格坐标
        DrawUtils.drawYPercentAndPrice(this,canvas, yMax, yMin, yd,mWidth, mainH);
        //画下面的时间
        DrawUtils.drawXTime(this,canvas, data.getParam().getDuration(), data.getParam().getUntil(),mWidth, mainH);
        if(crossView.getVisibility() == GONE)
        {
            drawZhiBiao(canvas);
        }

    }
    public void drawZhiBiao(Canvas canvas)

    {

        long max = 0;
        for(CMinute minute : minutes) {
            max = minute.getCount() > max ? minute.getCount() : max;
        }
        CrossBean bean = new CrossBean(0,0);
        bean.indexText = new String[]{"最大成交量:" , max+""};
        bean.indexColor = new int[]{new ColorUtil2(this).getTextColor2(),new ColorUtil2(this).getTextColor7()};

        if(bean.indexText == null || bean.indexColor == null) return;
        Paint p = new Paint();
        p.setAntiAlias(true);
        p.setTextSize(26f);
        float x = 10;
        float y = getHeight() * (ChartConstant.MAIN_SCALE + ChartConstant.TIME_SCALE) + 23;
        for(int i = 0;i < bean.indexText.length; i++) {
            p.setColor(bean.indexColor[i]);
            canvas.drawText(bean.indexText[i], x, y, p);
            x += LineUtil.getTextWidth(p, bean.indexText[i]) + 30;
        }


    }

    /**
     * 画背景
     * @param canvas
     */
    private void drawBack(Canvas canvas)
    {   if(price==null)
      {
        return;
      }
        double[] maxAndMin = LineUtil.getMaxAndMinByYd(yMax, yMin, yd);


        float width = price.length*xUnit;
        float height = mainH;
        Paint paint = new Paint();
        LinearGradient backGradient = new LinearGradient(0, 0, 0, height,0xffACC9FC,0x00ffffff, Shader.TileMode.CLAMP);
        paint.setShader(backGradient);



//        Paint paint2=new Paint();//创建一个采用默认设置的画笔
//        paint2.setColor(0x80ffffff);//设置画笔颜色
//        paint2.setAntiAlias(true);//使用抗锯齿功能
//        paint2.setStyle(Paint.Style.FILL);//设置填充方式为描边


        float max=(float) maxAndMin[0];
        float min=(float) maxAndMin[1];
        float yUnit = (max - min) / height;
        Path pathTr=new Path();
        for(int i=0;i<price.length;i++)
        {
            if(i==0)
            {
                pathTr.moveTo(i * xUnit,DrawUtils.getY(mainH,price[i],min,yUnit));
            }
            else
            {
                pathTr.lineTo(i * xUnit,DrawUtils.getY(mainH,price[i],min,yUnit));

            }
        }
        if(price.length<=0)
        {
            return;
        }
        pathTr.lineTo(price.length*xUnit,mainH);
        pathTr.lineTo(0,mainH);
        pathTr.lineTo(0,DrawUtils.getY(mainH,price[0],min,yUnit));
        canvas.drawPath(pathTr, paint);

        //canvas.drawRect(0, 0, width, height, paint);

    }
    @Override
    protected void drawLines(Canvas canvas) {
        if(minutes == null||minutes.size()==0) return;
        index=LineUtil.getIndexs(minutes);
        price = new float[minutes.size()];
        average = new float[minutes.size()];
        for(int i = 0; i < minutes.size(); i++) {
            price[i] = (float) minutes.get(i).getPrice();
            average[i] = (float) minutes.get(i).getAverage();
        }
        //根据数据顺序为x坐标
        //drawPriceLine(canvas);
        //drawAverageLine(canvas);
        //drawBack(canvas);

        //根据时间为x坐标
        drawPriceLine2(canvas);
        drawBack2(canvas);
        drawAverageLine2(canvas);
    }

    @Override
    protected void drawVOL(Canvas canvas) {
        if(minutes == null) return;
        long max = 0;
        for(CMinute minute : minutes) {
            max = minute.getCount() > max ? minute.getCount() : max;
        }
        //如果量全为0，则不画
        if(max != 0) {
            //2,画量线，多条竖直线
            //DrawUtils.drawVOLRects(canvas, xUnit, indexStartY, indexH, max, (float) data.getParam().getLast(), minutes);
            DrawUtils.drawVOLRects3(canvas, xUnit, indexStartY, indexH, max, (float) data.getParam().getLast(), minutes,index);
        }
    }

    @Override
    protected void drawZJ(Canvas canvas) {
    }

    /**
     * 价格线
     * @param canvas
     */
    private void drawPriceLine(Canvas canvas) {
        //乘以1.001是为了让上下分别空一点出来
        double[] maxAndMin = LineUtil.getMaxAndMinByYd(yMax, yMin, yd);
        DrawUtils.drawLines(canvas, price,xUnit , mainH, ColorUtil.COLOR_PRICE_LINE, (float) maxAndMin[0], (float) maxAndMin[1], false);
    }

    /**
     * 根据时间为坐标来划线
     * @param canvas
     */
    private void drawPriceLine2(Canvas canvas) {

        for(int i = 0; i < minutes.size(); i++) {
            price[i] = (float) minutes.get(i).getPrice();
            average[i] = (float) minutes.get(i).getAverage();
        }


        float[] maxAndMin1 = LineUtil.getMaxAndMin(average);
        //如果均线值全为0.01则不画改线，否则会影响价格线展示
//        if(1==1)
//        {
//            return;
//        }
        if(maxAndMin1[0] == 0.01 && maxAndMin1[1] == 0.01)
            return;
        //乘以1.001是为了让上下分别空一点出来
        double[] maxAndMin = LineUtil.getMaxAndMinByYd(yMax, yMin, yd);
//        DrawUtils.drawPriceShader(canvas, price, xUnit, mainH, (float) maxAndMin[0], (float) maxAndMin[1]);
        DrawUtils.drawLines3(canvas, price,index ,xUnit, mainH, new ColorUtil2(this).getYinYincolor2(), (float) maxAndMin[0], (float) maxAndMin[1]);
    }

    /**
     * 画背景
     * @param canvas
     */
    private void drawBack2(Canvas canvas)
    {   if(price==null)
    {
        return;
    }

        if(index[0]>9)
        {
            return;
        }
        double[] maxAndMin = LineUtil.getMaxAndMinByYd(yMax, yMin, yd);


        float width = price.length*xUnit;
        float height = mainH;
        Paint paint = new Paint();
        LinearGradient backGradient = new LinearGradient(0, 0, 0, height,new ColorUtil2(this).getYinYincolor2(),0x00ffffff, Shader.TileMode.CLAMP);
        paint.setShader(backGradient);



//        Paint paint2=new Paint();//创建一个采用默认设置的画笔
//        paint2.setColor(0x80ffffff);//设置画笔颜色
//        paint2.setAntiAlias(true);//使用抗锯齿功能
//        paint2.setStyle(Paint.Style.FILL);//设置填充方式为描边


        float max=(float) maxAndMin[0];
        float min=(float) maxAndMin[1];
        float yUnit = (max - min) / height;
        Path pathTr=new Path();
        for(int i=0;i<price.length;i++)
        {
            if(i==0)
            {
                pathTr.moveTo(index[i] * xUnit,DrawUtils.getY(mainH,price[i],min,yUnit));
            }
            else
            {
                pathTr.lineTo(index[i] * xUnit,DrawUtils.getY(mainH,price[i],min,yUnit));

            }
        }
        if(price.length<=0)
        {
            return;
        }
        pathTr.lineTo(index[index.length-1]*xUnit,mainH);
        pathTr.lineTo(index[0]*xUnit,mainH);
        pathTr.lineTo(index[0]*xUnit,DrawUtils.getY(mainH,price[0],min,yUnit));
        canvas.drawPath(pathTr, paint);

        //canvas.drawRect(0, 0, width, height, paint);

    }
    private void drawAverageLine2(Canvas canvas) {

        float[] maxAndMin1 = LineUtil.getMaxAndMin(average);
        //如果均线值全为0.01则不画改线，否则会影响价格线展示
//        if(1==1)
//        {
//            return;
//        }
        if(maxAndMin1[0] == 0.01 && maxAndMin1[1] == 0.01)
            return;
        //乘以1.001是为了让上下分别空一点出来
        double[] maxAndMin = LineUtil.getMaxAndMinByYd(yMax, yMin, yd);
//        DrawUtils.drawPriceShader(canvas, price, xUnit, mainH, (float) maxAndMin[0], (float) maxAndMin[1]);
        DrawUtils.drawLines3(canvas, average,index,xUnit, mainH, ColorUtil.COLOR_SMA_LINE, (float) maxAndMin[0], (float) maxAndMin[1]);
    }
    private void drawAverageLine(Canvas canvas) {

        float[] maxAndMin1 = LineUtil.getMaxAndMin(average);
        //如果均线值全为0.01则不画改线，否则会影响价格线展示
//        if(1==1)
//        {
//            return;
//        }
        if(maxAndMin1[0] == 0.01 && maxAndMin1[1] == 0.01)
            return;
        //乘以1.001是为了让上下分别空一点出来
        double[] maxAndMin = LineUtil.getMaxAndMinByYd(yMax, yMin, yd);
//        DrawUtils.drawPriceShader(canvas, price, xUnit, mainH, (float) maxAndMin[0], (float) maxAndMin[1]);
        DrawUtils.drawLines(canvas, average, xUnit, mainH, ColorUtil.COLOR_SMA_LINE, (float) maxAndMin[0], (float) maxAndMin[1], false);
    }
    /**
     * 设置价格精度
     */
    public void setScalePrice(int scale_price)
    {
        this.scale_price=scale_price;
    }
    /**
     * 当十字线移动到某点时，回调到此处，用此处的数据判断是否显示十字线
     * @param x x轴坐标
     * @param y y轴坐标
     */
    @Override
    public void onCrossMove(float x, float y) {
        super.onCrossMove(x, y);
        if(crossView == null || minutes == null) return;
        invalidate();
        CMinute cMinute=null;
        int position = (int) Math.rint(new Double(x)/ new Double(xUnit));
        if (index == null || index.length == 0) {
            return;
        }
        if(position<index[0])
        {

            cMinute = minutes.get(0);
            position=index[0];
        }
        else if(position>index[index.length-1])
        {

            position=minutes.size()-1;
            cMinute = minutes.get(position);
            position=index[index.length-1];
        }
//        if(position < minutes.size()) {
//            if (position < 0) {
//                return;
//            }
//            cMinute = minutes.get(position);
//        }
        else
        {
            int a=LineUtil.getIndex(position,index);
            if(a<0)
            {
                return;
            }
            cMinute = minutes.get(a);
        }
        //如果y轴移动的时间轴  则不画
        if(y>mainH&&y<indexStartY)
        {
            return;
        }
        if(y>mHeight)
        {
            return;
        }
        if(y<0)
        {
            y=0;
        }
        float cy = (float) getY(cMinute.getPrice());
        //CrossBean bean = new CrossBean(position * xUnit, cy);
        CrossBean bean = new CrossBean(position * xUnit, y);
        bean.y2 = (float) getY(cMinute.getAverage());
        // bean.price = cMinute.getPrice() + "";
        bean.price = NumberUtil2.getString(getPrice(y)+"","1",scale_price);
        if(y>indexStartY)
        {
            bean.price=getZhiBiaoValue(y);
        }
        bean.time = cMinute.getTime();
        setIndexTextAndColor(position, cMinute, bean);
        crossView.drawLine(bean);
        if(crossView.getVisibility() == GONE)
            crossView.setVisibility(VISIBLE);
        //TODO 此处把该点的数据写到界面上
        // msgText.setVisibility(VISIBLE);
        // msgText.setText(Html.fromHtml(getCurPriceInfo(cMinute)));
        msgText.icb.call(cMinute,x,y);
    }

    @Override
    public void onDismiss() {
        Log.e("t","t5");
        msgText.setVisibility(GONE);
        msgText.icb.cancle(null);
        invalidate();
    }

    /**
     * 计算指标左上角应该显示的文字
     */
    private void setIndexTextAndColor(int position, CMinute cMinute, CrossBean bean) {
        switch (indexType) {
            case INDEX_VOL:
                String count=NumberUtil2.getString(cMinute.getCount()+"","1",0);
                bean.indexText = new String[]{"成交量:" ,count};
                bean.indexColor = new int[]{new ColorUtil2(this).getTextColor2(),new ColorUtil2(this).getTextColor7()};
                break;
            case INDEX_ZJ:

                break;
        }
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
//        Log.e("t","t6");
//        if(crossView != null)
//            crossView.setVisibility(GONE);
    }

    //获取价格对应的Y轴
    private double getY(double price) {
        double[] maxAndMin = LineUtil.getMaxAndMinByYd(yMax, yMin, yd);
        if(price == maxAndMin[0]) return 0;
        if(price == maxAndMin[1]) return mainH;
        return mainH - (new Float(price) - maxAndMin[1]) / ((maxAndMin[0] - maxAndMin[1]) / mainH);
    }
    OnClickListener ocl;
    public void setSingOn(OnClickListener ocl)
    {
        this.ocl=ocl;
    }
    @Override
    public void singleOn(MotionEvent e) {
        if(ocl!=null)
        {
            ocl.onClick(null);
        }


    }

    /**
     * 价格信息
     *
     * @param entity
     * @return
     */
    public String getCurPriceInfo(CMinute entity) {
        return ColorUtil.getCurPriceInfo(entity, yd);
    }


    /**
     * 根据y轴坐标 计算对应的价格
     * @param y
     * @return
     */
    public float getPrice(float y)
    {

        float f1=mainH - y;
        f1=(float) (f1*yUnit+yMin);

        return  f1;
    }

    /**
     * 得到指标的值
     * @param y
     * @return
     */
    private String getZhiBiaoValue(float y) {

        if (indexType == INDEX_VOL) {
            double max = 0;
            for (CMinute data : minutes) {
                max = data.getCount() > max ? data.getCount() : max;
            }
            String s1 = DrawUtils.getVolValue(max, y, indexH, indexStartY);
            s1 = NumberUtil2.getString(s1 + "", "1", 0);
            return s1;

        }
        return null;
    }
}
